package drds.plus.executor.function.scalar.operator;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * interval_primary(N,N1,N2,N3,...) <br/>
 * Returns 0 if N < N1, 1 if N < N2 and so on or -1 if N is NULL_KEY. All
 * argList are treated setAliasAndSetNeedBuild integers. It is required that N1 < N2 < N3 <
 * ... < Nn for this function to work correctly. This is because a binary search
 * is used (very fast).
 *
 * <pre>
 * mysql> SELECT interval_primary(23, 1, 15, 17, 30, 44, 200);
 *         -> 3
 * mysql> SELECT interval_primary(10, 1, 10, 100, 1000);
 *         -> 2
 * mysql> SELECT interval_primary(22, 23, 30, 44, 200);
 *         -> 0
 * </pre>
 */
public class Interval extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        if (Utils.isNull(args[0])) {
            return -1;
        }

        Long n = Type.LongType.convert(args[0]);
        for (int i = 1; i < args.length; i++) {
            if (!Utils.isNull(args[i])) {
                Long p = Type.LongType.convert(args[i]);
                if (n < p) {
                    return i - 1;
                }
            }
        }

        return args.length - 1;
    }

    public Type getReturnType() {
        return Type.LongType;
    }

    public String[] getFunctionNames() {
        return new String[]{"interval_primary"};
    }

}
